//
//  CommonWebServices.m
//  HuateVideo
//
//  Created by Tiger on 12-6-24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CommonWebServices.h"
#import "AppDelegate.h"
#import "XMLDeserializer.h"

#define TIME_OUT 30.0f
#define HTTP_HOST [@"http://" stringByAppendingString:HOST]
#define REQUEST_URL [HTTP_HOST stringByAppendingString:@"/%@.asmx"]
//#define REQUEST_DEFAULT_URL [HTTP_HOST stringByAppendingString:@":81/%@.asmx"]
#define BASE_REQUEST_XML @"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Header> <MySoapHeader xmlns=\"http://tempuri.org/\"> <User>TempUser</User> <Pass>159226</Pass> </MySoapHeader> </soap:Header> <soap:Body> %@ </soap:Body> </soap:Envelope>"
#define DEFAULT_BASE_REQUEST_XML @"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"> <soap:Body> %@ </soap:Body> </soap:Envelope>"
#define BASE_XML @"<%@>%@</%@>"
#define ACTION_XML @"<%@ xmlns=\"%@\">%@</%@>"

@implementation CommonWebServices

@synthesize delegate;
@synthesize webData;
@synthesize connection;
@synthesize tag;

- (void)dealloc{
    
    [webData release];
    [connection cancel];
    [connection release];
    [super dealloc];
}

- (NSString *)dictionaryToXML:(id)dic {
    NSMutableString *valueString = [[NSMutableString alloc]init];
    
    if ([dic isKindOfClass:[NSDictionary class]]) {
        for(NSString *key in [dic allKeys]) {
            NSString *value = [dic objectForKey:key];
            NSString *paramString = [NSString stringWithFormat:BASE_XML,key,value,key];
            [valueString appendString:paramString];
        }
    }
    
    return [valueString autorelease];
}

- (void)paserXmlDataToCustomClass{
    
    NSString *responseString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
//    NSLog(@"Response String >>>>>:%@",responseString);
    
    NSString* trimmedXML0 = [self trimXML:responseString];
    NSString* trimmedXML = [NSString stringWithString:trimmedXML0];
    [responseString release];
    
    
    Class objectClass = NSClassFromString(_className);
    XMLDeserializer* deserializer = [[XMLDeserializer alloc] initWithClass:[objectClass class] 
																   xmlData:[trimmedXML dataUsingEncoding:NSUTF8StringEncoding] 
															   elementName:_className];
	id object = [deserializer deserialize];
    
    if ([self.delegate respondsToSelector:@selector(onCommonWebServicesWithCustomClass:)]) {
        
        [self.delegate onCommonWebServicesWithCustomClass: object];
    }
    if ([self.delegate respondsToSelector:@selector(onCommonWebServicesWithCustomClass: tag:)]) {
        
        [self.delegate onCommonWebServicesWithCustomClass: object tag:self.tag];
    }
}

- (void)startRequestWithMode:(NSString *)mode Action:(NSString *)action Parma:(id)parma Class:(NSString *)className RootXML:(NSString *)rootXML resultIsArray:(BOOL)isArray{
    
    if (!LOCALSWITCH) {
        mode = @"UygurDefault";
    }
    
    _rootXML = [rootXML retain];
    _className = [className retain];
    _isArray = isArray;
    NSString *requestUrlUTF8 = [NSString stringWithFormat:REQUEST_URL,mode];
    NSString *soapActionHeader = @"http://tempuri.org/";
    
    
    
    //if ([mode isEqualToString:@"Default"]) {
        //requestUrlUTF8 = [NSString stringWithFormat:REQUEST_DEFAULT_URL,mode];
    //}
    
    //NSLog(@"Action url>>>>>:%@",requestUrlUTF8);
	
	NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:requestUrlUTF8]];
	
    NSString *variable = [self dictionaryToXML:parma];
    NSString *withAction = [NSString stringWithFormat:ACTION_XML,action,soapActionHeader,variable,action];
    NSString *strBody = [NSString stringWithFormat:BASE_REQUEST_XML,withAction];
    
    if ([mode isEqualToString:@"Default"] || [mode isEqualToString:@"ClientInfo"]) {
        strBody = [NSString stringWithFormat:DEFAULT_BASE_REQUEST_XML,withAction];
    }
    
    [urlRequest setHTTPMethod:@"POST"];
	[urlRequest setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[urlRequest setValue:[NSString stringWithFormat:@"%@%@",soapActionHeader,action] forHTTPHeaderField:@"SOAPAction"];
	[urlRequest setValue:HOST forHTTPHeaderField:@"Host"];
	[urlRequest setValue:[NSString stringWithFormat:@"%d",[strBody length]] forHTTPHeaderField:@"Content-Length"];	
	
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[strBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
    [urlRequest setHTTPBody:postBody];
    
	[urlRequest setTimeoutInterval:TIME_OUT];
	[urlRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	
	connection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate:self];
	
	if (connection) {
        webData = [[NSMutableData data] retain];
		
		if ([self.delegate respondsToSelector:@selector(openActiovityIndicator)]) {
			[self.delegate openActiovityIndicator];
		}
        
		[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	}
}

- (void)cancelRequest {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    
    if ([self.delegate respondsToSelector:@selector(closeActiovityIndicator)]) {
        [self.delegate closeActiovityIndicator];
    }
    
	if (self.connection!=nil) {
		[self.connection cancel];
		self.connection = nil;
	}
    
    self.webData = nil;
	self.delegate = nil;
    
    
}

- (NSString *)trimXML:(NSString *)xml
{
	NSString *root_str1 = [NSString stringWithFormat:@"<%@",_rootXML];
    NSString *root_str2 = [NSString stringWithFormat:@"/%@>",_rootXML];
    
    NSString *class_str1;
    NSString *class_str2;
    if (_isArray) {
        class_str1 = [NSString stringWithFormat:@"<%@><List",_className];
        class_str2 = [NSString stringWithFormat:@"/List></%@>",_className];
    }
    else {
        class_str1 = [NSString stringWithFormat:@"<%@",_className];
        class_str2 = [NSString stringWithFormat:@"/%@>",_className];
    }
    
	NSString* trimmedXML1 = [xml stringByReplacingOccurrencesOfString:root_str1 withString:class_str1];
	NSString* trimmedXML2 = [trimmedXML1 stringByReplacingOccurrencesOfString:root_str2 withString:class_str2];
    
	return trimmedXML2;
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	
    NSHTTPURLResponse * httpResponse;
    httpResponse = (NSHTTPURLResponse *) response;
    
    if (httpResponse.statusCode != 200) {
		
        NSLog(@"httpResponse statusCode >>>>>>:%d",httpResponse.statusCode);
        
        if ([self.delegate respondsToSelector:@selector(onCommonWebServicesFaild)]) {
			[self.delegate onCommonWebServicesFaild];
		}
		
		if ([self.delegate respondsToSelector:@selector(closeActiovityIndicator)]) {
			[self.delegate closeActiovityIndicator];
		}
		
		[self cancelRequest];
        
    }else {
		[self.webData setLength: 0];
	}
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [self.webData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
	
    if ([self.delegate respondsToSelector:@selector(onCommonWebServicesFaild)]) {
		[self.delegate onCommonWebServicesFaild];
	}
	
	if ([self.delegate respondsToSelector:@selector(closeActiovityIndicator)]) {
		[self.delegate closeActiovityIndicator];
	}
	
	[self cancelRequest];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	
	if (self.webData!=nil && [self.webData length]>0) {
        
        [self paserXmlDataToCustomClass];
        
	}else {
        NSLog(@"responseData nil");
    }
	
	if ([self.delegate respondsToSelector:@selector(closeActiovityIndicator)]) {
		[self.delegate closeActiovityIndicator];
	}
	
	[self cancelRequest];
}

@end
